package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.entity.*;
import com.itheima.reggie.mapper.OrderMapper;
import com.itheima.reggie.service.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

@Service
@Slf4j
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Orders> implements OrderService {
    @Autowired
    private ShoppingCartService shoppingCartService;

    @Autowired
    private UserService userService;

    @Autowired
    private AddressBookService addressBookService;

    @Autowired
    private OrderDetailService orderDetailService;

    /**
     * 用户下单
     *
     * @param orders
     */
    @Transactional
    public void submit(Orders orders) {
        //获得当前用户id
        Long userId = BaseContext.getCurrentId();
        //1查询当前用户的购物车数据
        LambdaQueryWrapper<ShoppingCart> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ShoppingCart::getUserId, userId);
        //当前用户购物车的数据
        List<ShoppingCart> shoppingCarts = shoppingCartService.list(queryWrapper);
        //判断购物车是否为空，为空抛出异常
        //2根据当前登录用户id, 查询用户数据
        User user = userService.getById(userId);
        //3查询根据地址ID
        Long addressBookId = orders.getAddressBookId();
        //查询地址数据
        AddressBook addressBook = addressBookService.getById(addressBookId);
        //判断用户地址数据是否为空，为空抛出异常

        long orderId = IdWorker.getId();//订单号
        //定义一个结账总金额的变量
        AtomicInteger amount = new AtomicInteger(0);
        //4组装订单明细数据, 批量保存订单明细
        List<OrderDetail> orderDetails = shoppingCarts.stream().map(item -> {
            OrderDetail orderDetail = new OrderDetail();
            orderDetail.setOrderId(orderId);                    //设置订单id
            orderDetail.setNumber(item.getNumber());            //设置数量
            orderDetail.setDishFlavor(item.getDishFlavor());    //设置菜品口味
            orderDetail.setDishId(item.getDishId());            //设置菜品
            orderDetail.setSetmealId(item.getSetmealId());      //设置套餐id
            orderDetail.setName(item.getName());                //设置名字
            orderDetail.setImage(item.getImage());              //设置图片
            orderDetail.setAmount(item.getAmount());            //设置结账金额
            amount.addAndGet(item.getAmount().multiply(new BigDecimal(item.getNumber())).intValue());
            return orderDetail;
        }).collect(Collectors.toList());
        //5组装订单数据, 批量保存订单数据
        orders.setId(orderId);                              //设置订单号
        orders.setOrderTime(LocalDateTime.now());           //设置下单时间
        orders.setCheckoutTime(LocalDateTime.now());        //设置结账时间
        orders.setStatus(2);                                //设置订单状态
        orders.setAmount(new BigDecimal(amount.get()));     //总金额
        orders.setUserId(userId);                           //设置下单用户id
        orders.setNumber(String.valueOf(orderId));          //设置数量
        orders.setUserName(user.getName());                 //设置用户名
        orders.setConsignee(addressBook.getConsignee());    //设置收货人
        orders.setPhone(addressBook.getPhone());            //设置手机号
        //设置收货地址
        orders.setAddress((addressBook.getProvinceName() == null ? "" : addressBook.getProvinceName())
                + (addressBook.getCityName() == null ? "" : addressBook.getCityName())
                + (addressBook.getDistrictName() == null ? "" : addressBook.getDistrictName())
                + (addressBook.getDetail() == null ? "" : addressBook.getDetail()));
        //向订单表插入数据，一条数据
        this.save(orders);

        //向订单明细表插入数据，多条数据
        orderDetailService.saveBatch(orderDetails);
        //6删除当前用户的购物车列表数据
        shoppingCartService.remove(queryWrapper);
    }
}